const { Category } = require('@models');
const { Op } = require('sequelize');
const { ApiResponse } = require('@shared/utils/response');
const CategoryService = require('@services/category/category.service');

class CategoryController {
  constructor() {
    // 绑定所有方法的this
    this.getCategories = this.getCategories.bind(this);
    this.getAllCategories = this.getAllCategories.bind(this);
    this.getCategoryTree = this.getCategoryTree.bind(this);
    this.getCategory = this.getCategory.bind(this);
    this.createCategory = this.createCategory.bind(this);
    this.updateCategory = this.updateCategory.bind(this);
    this.deleteCategory = this.deleteCategory.bind(this);
    this.updateStatus = this.updateStatus.bind(this);
    this.updateCategorySort = this.updateCategorySort.bind(this);
  }

  /**
   * 获取分类列表
   */
  async getCategories(req, res) {
    try {
      const {
        page = 1,
        pageSize = 10,
        name,
        status
      } = req.query;

      // 构建查询条件
      const where = {};
      
      // 处理名称模糊查询
      if (name && name.trim()) {
        where.name = {
          [Op.like]: `%${name.trim()}%`
        };
      }
      
      // 处理状态查询
      if (status !== undefined && status !== '' && status !== null) {
        where.status = parseInt(status);
      }

      console.log('查询条件:', where);

      // 执行查询
      const { count, rows } = await Category.findAndCountAll({
        where,
        order: [['sort', 'ASC'], ['id', 'ASC']],
        offset: (parseInt(page) - 1) * parseInt(pageSize),
        limit: parseInt(pageSize)
      });

      // 格式化返回数据
      const formattedRows = rows.map(row => ({
        id: row.id,
        name: row.name,
        sort: row.sort,
        status: row.status,
        create_time: row.create_time,
        update_time: row.update_time
      }));

      return res.json(ApiResponse.success({
        list: formattedRows,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }));
    } catch (error) {
      console.error('获取分类列表失败:', error);
      return res.json(ApiResponse.error('获取分类列表失败：' + error.message));
    }
  }

  /**
   * 获取所有分类（不分页）
   */
  async getAllCategories(req, res) {
    try {
      const categories = await Category.findAll({
        where: { status: 1 },
        order: [['sort', 'ASC'], ['id', 'ASC']]
      });
      return res.json(ApiResponse.success(categories));
    } catch (error) {
      console.error('获取所有分类失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 获取分类树形结构
   */
  async getCategoryTree(req, res) {
    try {
      const result = await CategoryService.getCategoryTree();
      return res.json(ApiResponse.success(result));
    } catch (error) {
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 获取分类详情
   */
  async getCategory(req, res) {
    try {
      const category = await CategoryService.getCategoryById(req.params.id);
      if (!category) {
        return res.json(ApiResponse.notFound('分类不存在'));
      }
      return res.json(ApiResponse.success({ list: [category], total: 1 }));
    } catch (error) {
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 创建分类
   */
  async createCategory(req, res) {
    try {
      const category = await Category.create(req.body);
      return res.json(ApiResponse.success(category));
    } catch (error) {
      console.error('创建分类失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 更新分类
   */
  async updateCategory(req, res) {
    try {
      const { id } = req.params;
      const category = await Category.findByPk(id);
      if (!category) {
        return res.json(ApiResponse.notFound('分类不存在'));
      }
      await category.update(req.body);
      return res.json(ApiResponse.success(category));
    } catch (error) {
      console.error('更新分类失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 删除分类
   */
  async deleteCategory(req, res) {
    try {
      const { id } = req.params;
      const category = await Category.findByPk(id);
      if (!category) {
        return res.json(ApiResponse.notFound('分类不存在'));
      }
      await category.destroy();
      return res.json(ApiResponse.success(null, '删除成功'));
    } catch (error) {
      console.error('删除分类失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 更新分类状态
   */
  async updateStatus(req, res) {
    try {
      const { id } = req.params;
      const { status } = req.body;
      const category = await Category.findByPk(id);
      if (!category) {
        return res.json(ApiResponse.notFound('分类不存在'));
      }
      await category.update({ status });
      return res.json(ApiResponse.success(null, '状态更新成功'));
    } catch (error) {
      console.error('更新分类状态失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 更新分类排序
   */
  async updateCategorySort(req, res) {
    try {
      const category = await CategoryService.updateCategorySort(req.params.id, req.body.sort);
      if (!category) {
        return res.json(ApiResponse.notFound('分类不存在'));
      }
      return res.json(ApiResponse.success({ list: [category], total: 1 }));
    } catch (error) {
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 获取分类（适用于小程序）
   * 此方法返回的数据格式与小程序前端兼容
   */
  async getCategoriesForMiniapp(req, res) {
    try {
      // 查询所有状态为启用的分类
      const categories = await Category.findAll({
        where: { status: 1 },
        order: [['sort', 'ASC'], ['id', 'ASC']]
      });

      // 转换为小程序需要的格式
      const formattedCategories = categories.map(category => {
        const item = category.toJSON();
        // 确保图片字段存在
        if (!item.image) {
          item.image = '';
        }
        return item;
      });

      // 返回兼容小程序的数据格式
      return res.json({
        code: 200,
        message: 'success',
        data: formattedCategories
      });
    } catch (error) {
      console.error('获取小程序分类列表失败:', error);
      return res.status(500).json({
        code: 500,
        message: error.message || '获取分类列表失败',
        data: null
      });
    }
  }

  /**
   * 获取分类详情（适用于小程序）
   */
  async getCategoryForMiniapp(req, res) {
    try {
      const { id } = req.params;
      
      // 查询主分类
      const category = await Category.findOne({
        where: { id, status: 1 }
      });
      
      if (!category) {
        return res.status(404).json({
          code: 404,
          message: '分类不存在',
          data: null
        });
      }
      
      // 查询子分类
      const children = await Category.findAll({
        where: { parent_id: id, status: 1 },
        order: [['sort', 'ASC'], ['id', 'ASC']]
      });
      
      // 转换为小程序需要的格式
      const result = category.toJSON();
      
      // 确保图片字段存在
      if (!result.image) {
        result.image = '';
      }
      
      // 添加子分类
      result.children = children.map(child => {
        const item = child.toJSON();
        if (!item.image) {
          item.image = '';
        }
        return item;
      });
      
      return res.json({
        code: 200,
        message: 'success',
        data: result
      });
    } catch (error) {
      console.error('获取小程序分类详情失败:', error);
      return res.status(500).json({
        code: 500,
        message: error.message || '获取分类详情失败',
        data: null
      });
    }
  }
}

module.exports = new CategoryController(); 